package com.seari.gena.ciosServer;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.bean.BaseClient;
import com.seari.gena.bean.ServerBean;
import com.seari.gena.ciosServer.handler.CIOSNotifyClientHandler;
import com.seari.gena.ciosServer.handler.CIOSSender;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class CIOSNotifyClient extends BaseClient {
	protected static Logger logger = LoggerFactory.getLogger(CIOSNotifyClient.class);
	private ServerBean bean;

	public CIOSNotifyClient() {
		super();
	}

	public CIOSNotifyClient(String host, int port, ServerBean bean) {
		this.host = host;
		this.port = port;
		this.bean = bean;
	}

	@Override
	public void setup() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group) // 注册线程池
					.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
					.option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							logger.info("正在连接中...");
							ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
							ch.pipeline().addLast(new CIOSNotifyClientHandler(bean)); // 客户端触发操作
							ch.pipeline().addLast(new ByteArrayEncoder());
							ch.pipeline().addLast(new ChunkedWriteHandler());
						}
					});
			ChannelFuture cf = b.connect(host, port).sync(); // 异步连接服务器
			channel = cf.channel();
			logger.info("服务端连接成功..."); // 连接完成
			new CIOSSender(channel,bean).CiosSendData();

			cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
			logger.info("连接已关闭.."); // 关闭完成
		} finally {
			group.shutdownGracefully().sync(); // 释放线程池资源
		}
	}

	@Override
	public void reset() throws Exception {

	}
	public static void main(String[] args) throws Exception {
//		ServerBean bean = new ServerBean();
//		bean.setCallback("172.18.194.5:52225");
//		bean.setSid("Sid: " + System.currentTimeMillis());
//		bean.setNt("NT:gena:birth");
//		bean.setSubscribe("PowerSection");
//		CIOSNotifyClient client = new CIOSNotifyClient(bean.getCallback().split(":")[0], Integer.parseInt(bean.getCallback().split(":")[1]), bean);// 启动
//		client.setup();
	}

}
